package com.clei.Y2019.M06.D26;

import com.clei.utils.PrintUtil;
import com.clei.utils.helper.TableDataPrinter;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

import static com.clei.utils.PrintUtil.println;

/**
 * 获得本机的一些信息
 * 获得本地IP地址和主机名
 *
 * @author KIyA
 */
public class SystemPropertyTest {

    public static void main(String[] args) throws UnknownHostException {
        InetAddress addr = InetAddress.getLocalHost();
        println("IP:{}", addr.getHostAddress());
        println("主机名:{}", addr.getHostName());
        println("操作系统:{}", System.getProperty("os.name"));
        println("用户目录:{}", System.getProperty("user.dir"));
        println("系统位数(CPU架构):{}", System.getProperty("os.arch"));
        // 若是Sun/Oracle的JDK
        println("JDK位数:{}", System.getProperty("sun.arch.data.model"));
        // System Properties
        PrintUtil.separatorLine();
        PrintUtil.log("System Properties");
        Properties properties = System.getProperties();
        // 换行回车处理
        String lineSeparator = properties.getProperty("line.separator");
        lineSeparator = lineSeparator.replaceAll("\r", "\\\\r").replaceAll("\n", "\\\\n");
        properties.setProperty("line.separator", lineSeparator);
        Set<Map.Entry<Object, Object>> propertyEntries = properties.entrySet();
        List<List<String>> propertyList = new ArrayList<>(propertyEntries.size() + 1);
        for (Map.Entry<Object, Object> entry : propertyEntries) {
            String key = String.valueOf(entry.getKey());
            String value = String.valueOf(entry.getValue());
            propertyList.add(Arrays.asList(key, value));
        }
        // 排序
        propertyList.sort(Comparator.comparing(l -> l.get(0)));
        propertyList.add(0, Arrays.asList("Key", "Value"));
        TableDataPrinter printer = new TableDataPrinter();
        printer.print(propertyList);
        // Env Properties
        PrintUtil.separatorLine();
        PrintUtil.log("Env Properties");
        Map<String, String> envMap = System.getenv();
        List<List<String>> envList = new ArrayList<>(envMap.size() + 1);
        envMap.forEach((k, v) -> envList.add(Arrays.asList(k, v)));
        // 排序
        envList.sort(Comparator.comparing(l -> l.get(0)));
        envList.add(0, Arrays.asList("Key", "Value"));
        printer.print(envList);
    }
}
